package com.ytclub.auth.application.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.google.common.base.Preconditions;
import com.ytclub.auth.application.convent.AuthRolePermissionDTOConverter;
import com.ytclub.auth.application.dto.AuthRolePermissionDTO;
import com.ytclub.auth.domain.entity.AuthRolePermissionBO;
import com.ytclub.auth.domain.service.AuthRolePermissionDoaminService;
import com.ytclub.auth.entity.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * 角色权限控制层类
 *
 * @author: HuangQi
 * @date: Created in 14:56 2024/3/24
 * @description: 角色权限控制层
 */
@RestController
@RequestMapping("/rolePermission/")
@Slf4j
public class RolePermissionController {


    @Resource
    private AuthRolePermissionDoaminService authRolePermissionDoaminService;

    /**
     * 新增角色权限关联
     *
     * @param authRolePermissionDTO 新增角色权限关联的信息
     * @return 新增结果
     */
    @RequestMapping("add")
    public Result<Boolean> add(@RequestBody AuthRolePermissionDTO authRolePermissionDTO) {
        try {
            if (log.isInfoEnabled()) {
                log.info("RolePermissionController.add.dto:{}", JSON.toJSONString(authRolePermissionDTO));
            }
            // 参数校验
            Preconditions.checkArgument(!CollectionUtils.isEmpty(authRolePermissionDTO.getPermissionIdList()), "权限关联不能为空");

            Preconditions.checkNotNull(authRolePermissionDTO.getRoleId(), "角色id不能为空");


            // 调用领域层
            AuthRolePermissionBO authRolePermissionBO = AuthRolePermissionDTOConverter.INSTANCE.convertDTOToBO(authRolePermissionDTO);
            Boolean registerResult = authRolePermissionDoaminService.add(authRolePermissionBO);

            // 返回结果
            return Result.ok(registerResult);
        } catch (Exception e) {
            // 异常处理
            log.error("RolePermissionController.add.error:{}", e.getMessage(), e);
            return Result.fail("新增角色权限失败");
        }
    }
}
